package com.example.studentsystem.dao;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import androidx.constraintlayout.solver.widgets.Helper;

import com.example.studentsystem.bean.UserBean;
import com.example.studentsystem.db.MyHelper;

import java.util.ArrayList;
import java.util.List;

public class MyDao {
    Context context;
    MyHelper myHelper;
    List<UserBean> student;
    public MyDao(Context context){
        this.context = context;
        myHelper = new MyHelper(context);

    }
    public void insert(UserBean userBean){
        SQLiteDatabase db = myHelper.getWritableDatabase();
        db.execSQL("insert into STUDENT(id,name,sex,banji) values (?,?,?,?)",new Object[]{userBean.getId(),userBean.getName(),userBean.getSex(),userBean.getBanji()});
      db.close();
    }
    public void update(UserBean userBean){
        SQLiteDatabase db = myHelper.getWritableDatabase();
        System.out.println(userBean.getNum());
        db.execSQL("update STUDENT set id=?,name=?,sex=?,banji=? where num=?",new Object[]{userBean.getId(),userBean.getName(),userBean.getSex(),userBean.getBanji(),userBean.getNum()});
        db.close();
    }
    public void delete(UserBean userBean){
        SQLiteDatabase db = myHelper.getWritableDatabase();
        db.execSQL("delete from STUDENT where num=?",new Object[]{userBean.getNum()});
        db.close();
    }
    public List<UserBean> select(UserBean userBean){
        SQLiteDatabase db = myHelper.getReadableDatabase();
        String sql = "select * from STUDENT where 1=1 ";
        if(!"".equals(userBean.getName())&&userBean.getName()!=null){
            sql+=" and name like '%"+userBean.getName()+"%'";
        }
        List<UserBean> list = new ArrayList<>();
        Cursor cursor =  db.rawQuery(sql,new String[]{});
        if(cursor.getCount()>0){
            while (cursor.moveToNext()){
                @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
                @SuppressLint("Range") String sex = cursor.getString(cursor.getColumnIndex("sex"));
                @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));
                @SuppressLint("Range") int num = cursor.getInt(cursor.getColumnIndex("num"));
                @SuppressLint("Range") String banji = cursor.getString(cursor.getColumnIndex("banji"));
                UserBean testBean1 = new UserBean(num,id,name,sex,banji);
                list.add(testBean1);
            }
        }
        return list;
    }
}
